<?php

namespace app\api\controller;
use app\common\controller\Api;
use think\Validate;
use think\Loader;
use think\Page;
use think\Db;
use \app\admin\model\Banner;
use \app\manystore\model\Goods as GoodsModel;
use \app\manystore\model\Goodsspec;
use \app\admin\model\GoodsCategory;
use \app\manystore\model\ShopGoodsCategory;
use \app\manystore\model\ShopBanner;
class Goods extends Api
{ 
    protected $noNeedLogin = ['getbannerlist','getgoodslist','getgoodsinfo','getgoodscategory','getshopinfo','getshopgoodscategory','getshopbannerlist','getgoodscommentlist'];
    protected $noNeedRight = '*';
    protected $user_id = 0;
    protected $gmodel;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->gmodel = new GoodsModel;
    }

    /**
     * @MethodName 獲取商城banner圖
     * @Author     Allen
     * @DateTime   2021-10-04T14:59:51+0800
     * @param      string
     * @return     [type]
     */
    public function getBannerList($value='')
    {
        $model = new Banner;
        $list = $model
            ->field('id,image,type,relation_id,createtime')
            ->order('weigh desc,id desc')
            ->select();

        $this->success('請求成功',$list);
    }

    /**
     * [getGoodsList 獲取商品列表(普通商品和積分商品通用)]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T01:20:18+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getGoodsList($value='')
    {
        // 商品類型1正常商品2積分商品
        $type = $this->request->post("type", '1');
        // 商城商品分類
        $cat_id = $this->request->post("cat_id", 0);
        // 店鋪商品分類
        $shop_cat_id = $this->request->post("shop_cat_id", 0);
        // 搜索關鍵詞
        $ky = $this->request->post("ky", '');
        // 排序1綜合2銷量3價格
        $order_type = $this->request->post("order_type", '1');


        $where = ['type'=>$type,'goods_status'=>'10'];
        if ( $cat_id ) {
            $where['cat_id'] = $cat_id;
            $cmodel = new GoodsCategory;
            $f_cat = $cmodel->where(['id'=>$cat_id])->find();
            if ( $f_cat && $f_cat['parent_id'] == 0 ) {
                $cat_ids = $cmodel->where(['parent_id'=>$f_cat['id']])->column('id');
                $cat_ids[] = $cat_id;
                $where['cat_id'] = ['in',$cat_ids];
            }
        }
        if ( $ky ) {
            $where['goods_name'] = ['like',"%$ky%"];
        }
        if ( $shop_cat_id ) {
            $where['shop_cat_id'] = $shop_cat_id;
        }

        $field = 'goods_id,shop_id,images,goods_name';
        $order = 'goods_id desc';
        $spec_order = 'goods_price asc';
        switch ($order_type) {
            case '1':
                $order = 'goods_id desc';
                break;
            case '2':
                $order = 'sales_actual desc,goods_id desc';
                break;
            case '3':
                // 商品表名称
                $tableName = $this->gmodel->getTable();
                // 多规格商品最高價格
                $GoodsSpec = new Goodsspec();
                $maxPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
                    ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
                $order = 'goods_max_price asc,goods_id desc';
                $field .= ",$maxPriceSql AS goods_max_price";
                $spec_order = 'goods_price asc';
                break;
                
            
            default:
                $order = 'goods_id desc';
                break;
        }


        $total = $this->gmodel->where($where)->count();
        $page = new Page($total,10);

        $list = $this->gmodel
                ->field($field)
                ->where($where)
                ->limit($page->firstRow.','.$page->listRows)
                ->order($order)
                ->select();
        foreach ($list as $key => &$value) {
            unset($value->goods_max_price);
            $value['images'] = explode(',', $value['images'])[0];
            $value->line_price = 0;
            $value->goods_price = 0;
            $value->integral = 0;
            $min_price = db('goods_spec')->where(['goods_id'=>$value->goods_id])->order($spec_order)->find();
            if ( $min_price ) {
                $value->goods_price = $min_price['goods_price'];
                $value->line_price = $min_price['line_price'];
                $value->integral = $min_price['integral'];
            }

            $shop = db('manystore_shop s')
                    ->field('s.id as shop_id,logo,s.name,c.name as c_name')
                    ->join('goods_category c','c.id=s.cat_id','LEFT')
                    ->where(['s.id'=>$value['shop_id']])
                    ->find();

            $value['shop'] = $shop;

        }
        unset($value);

        $data = ['total'=>$total,'listrows'=>$page->listRows,'totalpages'=>$page->totalPages,'data'=>$list];
        $this->success('請求成功',$data);
    }

    /**
     * [getGoodsInfo 獲取商品詳情(普通商品和積分商品通用)]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T13:39:20+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getGoodsInfo($value='')
    {
        // 商品類型1正常商品2積分商品
        $goods_id = $this->request->post("goods_id", 0);
        if ( !$goods_id ) {
            $this->error('未找到該商品');
        }
        $detail = $this->gmodel->get($goods_id, [ 'spec', 'specRel']);
        if ( !$detail ) {
            $this->error('未找到該商品');
        }
        $detail['collection_status'] = db('collection')
                                    ->where(['type'=>'6','relation_id'=>$detail->goods_id,'user_id'=>$this->user_id])
                                    ->count();

        $shop = db('manystore_shop s')
                ->field('s.id as shop_id,logo,s.name,c.name as c_name')
                ->join('goods_category c','c.id=s.cat_id','LEFT')
                ->where(['s.id'=>$detail->shop_id])
                ->find();

        unset($detail->shop_id);
        unset($detail->cat_id);
        unset($detail->shop_cat_id);
        unset($detail->deduct_stock_type);
        unset($detail->sales_initial);
        unset($detail->deletetime);
        $imgs=[];
        foreach (explode(",",$detail['images']) as $index => $item) {
            $imgs[] = $item;
        }
        $detail['imgs_url'] = $imgs;

        if (!$detail || $detail['goods_status'] !== '10') {
            $this->error('很抱歉，商品信息不存在或已下架');
        }
        // 规格信息
        $specData = $detail['spec_type'] === '20' ? $detail->getManySpecData($detail['spec_rel'], $detail['spec']) : null;

        // 这里对规格的img格式化
        if($specData!=null){
            foreach($specData['spec_list'] as $index => $item){
                $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image']==='' ? $specData['spec_list'][$index]["form"]['spec_image']:'';
            }
        }


        unset($detail->spec_rel);
        $this->success('請求成功', [
                                'shop' => $shop,
                                'detail'  => $detail,
                                'specData' => $specData
                          ]);
    }

    /**
     * [getGoodsCommentList 獲取商品評論]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-18T00:33:49+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getGoodsCommentList($value='')
    {
        // 商品類型1正常商品2積分商品
        $goods_id = $this->request->post("goods_id", 0);
        $total = db('comment c')
                ->join('user u','u.id = c.user_id','LEFT')
                ->where(['c.goods_id'=>$goods_id])
                ->count();

        $page = new Page($total,10);

        $list = db('comment c')
                ->field('c.comment_id,u.nickname,u.avatar,c.content,c.goods_rank,c.goods_attr,c.createtime')
                ->join('user u','u.id = c.user_id','LEFT')
                ->where(['c.goods_id'=>$goods_id])
                ->limit($page->firstRow.','.$page->listRows)
                ->order('c.createtime desc')
                ->select();

        foreach ($list as $key => &$value) {
            $value['images'] = db('upload_images')
                            ->where(['type'=>'4','relation_id'=>$value['comment_id']])
                            ->limit(9)
                            ->column('images');

            unset($value['comment_id']);
        }
        unset($value);
        $data = ['total'=>$total,'listrows'=>$page->listRows,'totalpages'=>$page->totalPages,'data'=>$list];
        $this->success('請求成功',$data);
    }

    /**
     * [getGoodsCategory 獲取商城商品分類]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T14:45:29+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getGoodsCategory($value='')
    {
        // 類型1普通商品分類2積分商品分類
        $type = $this->request->post("type", 1);
        $model = new GoodsCategory;
        $list = $model
                ->field('id,name,image')
                ->where(['parent_id'=>0,'type'=>$type])
                ->order('weigh desc,id desc')
                ->select();

        foreach ($list as $key => $value) {
            $value['son'] = $model
                            ->field('id,name,image')
                            ->where(['parent_id'=>$value['id']])
                            ->order('weigh desc,id desc')
                            ->select();
        }

        $this->success('請求成功',$list);
    }

    /**
     * [getShopInfo 店鋪詳情]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T15:02:13+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getShopInfo($value='')
    {
        // 店鋪商品分類
        $shop_id = $this->request->post("shop_id", 0);
        if ( !$shop_id ) {
            $this->error('找不到該店鋪');
        }
        $shop = db('manystore_shop s')
                ->field('s.id as shop_id,logo,s.name,c.name as c_name')
                ->join('goods_category c','c.id=s.cat_id','LEFT')
                ->where(['s.id'=>$shop_id])
                ->find();

        $this->success('請求成功',$shop);
    }

    /**
     * [getShopGoodsCategory 店鋪商品分類]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T15:09:59+0800
     * @param      string                   $value [description]
     * @return     [type]                          [description]
     */
    public function getShopGoodsCategory($value='')
    {
        // 店鋪商品分類
        $shop_id = $this->request->post("shop_id", 0);

        $model = new ShopGoodsCategory;
        $list = $model
                ->field('id,name')
                ->where(['parent_id'=>0,'shop_id'=>$shop_id])
                ->order('weigh desc,id desc')
                ->select();

        $this->success('請求成功',$list);
    }

    /**
     * @MethodName 商品操作收藏
     * @Author     Allen
     * @DateTime   2021-10-04T16:13:20+0800
     * @param      string
     */
    public function setGoodsCollection($value='')
    {
        // 商品類型1正常商品2積分商品
        $goods_id = $this->request->post("goods_id", 0);
        if ( !$goods_id ) {
            $this->error('未找到該商品');
        }
        $detail = $this->gmodel->get($goods_id, [ 'spec', 'specRel']);
        if ( !$detail ) {
            $this->error('未找到該商品');
        }

        $collection_status = db('collection')
                            ->where(['type'=>'6','relation_id'=>$detail->goods_id,'user_id'=>$this->user_id])
                            ->count();

        if ( $collection_status ) {
            $status = db('collection')
                    ->where(['type'=>'6','relation_id'=>$detail->goods_id,'user_id'=>$this->user_id])
                    ->delete();
        }else{
            $insert_arr = [];
            $insert_arr['user_id'] = $this->user_id;
            $insert_arr['type'] = '6';
            $insert_arr['relation_id'] = $detail->goods_id;
            $insert_arr['createtime'] = time();
            $status = db('collection')->insert($insert_arr);
        }
        if ( !$status ) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }


    /**
     * @MethodName 獲取店鋪banner圖
     * @Author     Allen
     * @DateTime   2021-10-04T14:59:51+0800
     * @param      string
     * @return     [type]
     */
    public function getShopBannerList($value='')
    {
        $time = time();
        // 店鋪商品分類
        $shop_id = $this->request->post("shop_id", 0);

        $where = ['shop_id'=>$shop_id];
        $where['starttime'] = ['elt',$time];
        $where['endtime'] = ['egt',$time];
        $model = new ShopBanner;
        $list = $model
            ->field('id,image,createtime')
            ->where($where)
            ->order('weigh desc,id desc')
            ->select();

        $this->success('請求成功',$list);
    }


}